package cn.qhfn.servlet;

import cn.qhfn.entity.Pet;
import cn.qhfn.service.PetService;
import cn.qhfn.service.impl.PetServiceImpl;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/PetServlet")
public class PetServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String opr = req.getParameter("opr");
        PetService service = new PetServiceImpl();
        if ("add".equals(opr)) {
            String name = req.getParameter("name");
            String species = req.getParameter("species");
            int age = Integer.parseInt(req.getParameter("age"));
            Pet pet = new Pet();
            if (service.addPet(pet)) {
                out.print(1);
            }else {
                out.print(0);
            }
        } else if ("delete".equals(opr)) {
            int id = Integer.parseInt(req.getParameter("id"));
            if (service.deletePet(id)) {
                out.print(1);
            }else {
                out.print(0);
            }
        } else if ("update".equals(opr)) {
            int id = Integer.parseInt(req.getParameter("id"));
            String name = req.getParameter("name");
            String species = req.getParameter("species");
            int age = Integer.parseInt(req.getParameter("age"));
            Pet pet = new Pet();
            if (service.updatePet(pet)) {
                out.print(1);
            }else {
                out.print(0);
            }
        } else if ("queryById".equals(opr)) {
            int id = Integer.parseInt(req.getParameter("id"));
            Pet pet = service.getPet(id);
            out.print(JSON.toJSONString(pet));
        } else if ("query".equals(opr)) {
            List<Pet> pets = service.getPets();
            out.println(JSON.toJSONString(pets));
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
